﻿using System.ComponentModel;
using System.Linq.Expressions;

namespace LowCoding.Common
{
    public static class ModelExtensions
    {
        public static string GetFiledDescription<T>(this string FieldName)
        {
            try
            {
                Type Ts = typeof(T);
                return ((DescriptionAttribute)Attribute.GetCustomAttribute(Ts.GetProperty(FieldName), typeof(DescriptionAttribute))).Description;
            }
            catch (Exception ex)
            {
                ex.ToErrorLog();
                return "";
            }
        }

        public static string GetFiledValue(this string FieldName, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object o = Ts.GetProperty(FieldName).GetValue(obj, null);
                string Value = Convert.ToString(o);
                if (string.IsNullOrEmpty(Value)) return null;
                return Value;
            }
            catch
            {
                return null;
            }
        }

        public static string GetPropertyName<T>(Expression<Func<T, object>> expr)
        {
            var rtn = "";
            if (expr.Body is UnaryExpression)
            {
                rtn = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.Name;
            }
            else if (expr.Body is MemberExpression)
            {
                rtn = ((MemberExpression)expr.Body).Member.Name;
            }
            else if (expr.Body is ParameterExpression)
            {
                rtn = ((ParameterExpression)expr.Body).Type.Name;
            }
            return rtn;
        }

        public static int? IntOrNull(this string input)
        {
            if (input.IsInt())
            {
                return Convert.ToInt32(input);
            }
            else
            {
                return null;
            }
        }

        public static decimal? DecimalOrNull(this string input)
        {
            if (input.IsDecimal())
            {
                return Convert.ToDecimal(input);
            }
            else
            {
                return null;
            }
        }

        public static DateTime? DateTimeOrNull(this string input)
        {
            if (input.IsDate())
            {
                return Convert.ToDateTime(input);
            }
            else
            {
                return null;
            }
        }

        public static Boolean? BoolOrNull(this string input)
        {
            if (input.IsBool())
            {
                return Convert.ToBoolean(input);
            }
            else
            {
                return null;
            }
        }
    }
}